from flask import Blueprint, request, jsonify
from app.models.sync_log import SyncLog, SyncLogDetail
from app.models.sync_task import SyncTask

sync_log_bp = Blueprint('sync_log', __name__)

@sync_log_bp.route('/', methods=['GET'])
def get_sync_logs():
    """获取所有同步日志"""
    task_id = request.args.get('task_id', type=int)
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    query = SyncLog.query
    if task_id:
        query = query.filter_by(task_id=task_id)
    
    logs = query.order_by(SyncLog.start_time.desc()).paginate(page=page, per_page=per_page)
    
    return jsonify({
        'code': 200,
        'data': {
            'items': [log.to_dict() for log in logs.items],
            'total': logs.total,
            'page': logs.page,
            'pages': logs.pages,
            'per_page': logs.per_page
        }
    })

@sync_log_bp.route('/<int:id>', methods=['GET'])
def get_sync_log(id):
    """获取单个同步日志"""
    log = SyncLog.query.get_or_404(id)
    return jsonify({
        'code': 200,
        'data': log.to_dict()
    })

@sync_log_bp.route('/<int:id>/details', methods=['GET'])
def get_sync_log_details(id):
    """获取同步日志详情"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    status = request.args.get('status')
    
    query = SyncLogDetail.query.filter_by(log_id=id)
    if status:
        query = query.filter_by(status=status)
    
    details = query.paginate(page=page, per_page=per_page)
    
    return jsonify({
        'code': 200,
        'data': {
            'items': [{
                'id': detail.id,
                'log_id': detail.log_id,
                'record_id': detail.record_id,
                'status': detail.status,
                'error_message': detail.error_message,
                'created_at': detail.created_at.strftime('%Y-%m-%d %H:%M:%S')
            } for detail in details.items],
            'total': details.total,
            'page': details.page,
            'pages': details.pages,
            'per_page': details.per_page
        }
    })